<template>
  <div class="w_h_100" v-loading="loading" element-loading-text="奋力加载中">
    <div class="box">
      <div class="inlet">系统管理 > 流程管理 > <span class="size">流程管理</span></div>
      <myform :fields="fields" :model="values" class="m_t_10">
        <template v-slot:button>
          <el-button @click="resetting">重置</el-button>
          <el-button type="primary" :icon="Search" @click="searchFor">搜索</el-button>
        </template>
      </myform>
    </div>
    <div class="mytable m_t_10 ">
      <div class="d_f j_c_s_b a_i_c">
        <h4>流程列表</h4>
        <el-button type="primary" :icon="Plus" @click="addFlow" v-hasPerm="'addFlow'">新增流程</el-button>
      </div>
      <mytable :fields="tableFields" width="150" ref="tableRef" :values="values" api="flowFind" class="m_t_10"
        :isSelection="false">
        <template v-slot:status="{ row }">{{ row.status == 0 ? '未启用' : '启用' }}</template>
        <template v-slot:operation="{ row }">
          <div class="d_f j_c_s_b">
            <span class="edit" @click="replication(row)" v-hasPerm="'copyFlow'">复制</span>
            <span class="edit" @click="edit(row)" v-hasPerm="'editFlow'">{{row.status == 0?'编辑':'查看'}}</span>
            <span class="error" @click="deleteOut(row)" v-if="row.status == 0" v-hasPerm="'deleteFlow'">删除</span>
          </div>
        </template>
      </mytable>
    </div>
    <el-dialog v-model="copyShow" :title="copyTitle" width="400" :before-close="handleCloseCopy">
      <div class="d_f a_i_c f_d_c">
        <img src="../../../../assets/product.png" alt="" class="img">
        <div class="size">请输入新流程名称</div>
        <el-input v-model="model.name" placeholder="请输入" class="m_t_16"></el-input>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseCopy">取消</el-button>
          <el-button type="primary" @click="submit">
            复制
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, onBeforeMount, ref } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { copy } from '../../../../utils/date'
import { Message } from '../../../../utils/resetMessage'
import { ElMessageBox } from 'element-plus'
import { flowDel, flowCopy, flowGet, flowAdd } from '../../../../api/system/flowPath'
import { useRouter } from 'vue-router'
import {flowPathFlowType} from '../../../../type/system'
import { getRandNodeId, getRandNodeStart, getRandNodeEnd } from '../../../../utils/ProcessUtil.js'
const values = {
  name: ''
}
const model = {
  id: 0,
  name: '',
}
export default defineComponent({
  name: '',
  setup() {
    const data:flowPathFlowType = reactive({
      fields: [
        {
          label: "流程名称",
          prop: 'name',
          placeholder: '请输入',
          type: 'input',
          labelWidth: '96px'
        },
        {
          prop: 'button'
        }
      ],
      values: copy(values),
      tableFields: [
        {
          label: '流程名称',
          prop: 'name',
        },
        // {
        //   label: '流程标识',
        //   prop: 'code',
        // },
        {
          label: '状态',
          prop: 'status',
        },
        {
          label: '创建时间',
          prop: 'createdTime',
        },
      ],
      copyShow: false,
      copyTitle: '',
      model: copy(model),
      loading: false
    })
    const tableRef = ref()
    const router = useRouter()
    onBeforeMount(() => {
    })
    const methods = {
      //表格数据重置
      resetting() {
        data.values = copy(values)
        tableRef.value.resettingTable(data.values)
      },
      //列表根据筛选条件搜索
      searchFor() {
        tableRef.value.handleCurrentChange(1)
      },
      //删除当前流程
      deleteOut(row: any) {
        let val = `确认删除”${row.name}“`
        ElMessageBox.confirm(
          val,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
          }
        )
          .then(() => {
            flowDel({ id: row.id, status: row.status }).then(() => {
              Message({ type: 'success', message: '删除成功' })
              tableRef.value.handleCurrentChange(1)//添加表格之后重新获取表格
            })
          })
      },

      //新增流程
      addFlow() {
        router.push('/system/flowPath/flow/add')
      },
      //关闭复制弹窗
      handleCloseCopy() {
        data.model = copy(model)
        data.copyShow = false
      },
      //复制
      replication(row: any) {
        data.copyTitle = `复制“${row.name}”`
        data.model.id = row.id
        data.copyShow = true
      },
      //复制按钮提交
      submit() {
        data.loading = true
        flowGet({ id: data.model.id }).then((res: any) => {
          let list = methods.resetId(res.definition.process)//重置id
          let list1 = methods.resetPid(list, '', '')//根据重置的id找到对应的pid
          // let list2= methods.resetjumpNode(list1)
          let list2 = []
          methods.flatData(list1, list2)//过滤获取触发器的跳转节点，扁平数组
          methods.replacFlat(list1, list2)//根据扁平的数组，替换对应的jumpNode
          methods.resetjumpNode(list1, list2)
          const model = {
            name: data.model.name,
            process: list1,
            groupId: '',
            formConf: res.definition.formConf
          }
          flowAdd({tenantId:"",definition:model}).then(() => {
            data.loading = false
            Message({ type: 'success', message: '新增成功' })
            data.copyShow = false
            data.model = copy(model)
            tableRef.value.handleCurrentChange(1)//添加表格之后重新获取表格
          }).catch(()=>{
            data.loading=data.copyShow = false
          })
        })
      },
      resetId(arr) {
        arr.map((item: any, index: number) => {
          if (item.type == 'START') {
            item.hpid = item.id
            item.id = getRandNodeStart()

          } else if (item.type == 'END') {
            item.hpid = item.id
            item.id = getRandNodeEnd()
          } else {
            if (item.type == "GATEWAY") {
              // console.log(item);
              item.hpid = item.id
              item.id = getRandNodeId() + '_fork'
              console.log(item);
            } else {
              item.hpid = item.id
              item.id = getRandNodeId() + index
            }
          }
          if (item.props) {
            if (item.props.branch) {
              item.props.branch = methods.resetId(item.props.branch)
            }
          }
          if (item.branch) {
            if (item.branch.length > 0) {
              item.branch.map((item1: any) => {
                item1 = methods.resetId(item1)
              })
            }
          }
        })
        return arr
      },
      //判断数据里面有没有pid，没得pid再次递归查找pid
      resetPid(arr, json, name) {
        arr.map((item: any, index: number) => {
          if (!json) {
            if (item.type != 'START') {
              item.parentId = arr[index - 1].id
            }
          } if (json) {
            if (index == 0 || name) {
              item.parentId = json.id
            } else {
              item.parentId = arr[index - 1].id
            }
          }
          if (item.props) {
            if (item.props.branch) {
              item.props.branch = methods.resetPid(item.props.branch, item, "GATEWAY")
              if (item.branch) {
                if (item.branch.length > 0) {
                  item.branch.map((item1: any, index1: number) => {
                    if (item1.length > 0) {
                      item1 = methods.resetPid(item1, item.props.branch[index1], '')
                    }
                  })
                }
              }
            }
          }

        })
        return arr
      },
      //筛选跳转id的list，扁平数组
      flatData(arr, list2) {
        arr.map((item: any) => {
          if (item.type == 'TRIGGER') {
            list2.push(item)
          }
          if (item.props) {
            if (item.props.branch) {
              methods.flatData(item.props.branch, list2)
            }
          }
          if (item.branch) {
            if (item.branch.length > 0) {
              item.branch.map((item1: any) => {
                console.log(item1, list2);
                methods.flatData(item1, list2)
              })
            }
          }
        })
        return list2
      },
      replacFlat(arr, list2) {
        arr.map((item: any) => {
          list2.map((em: any) => {
            if (em.props.jumpNodeCode == item.hpid) {
              em.props.jumpNodeCode = item.id
            }
          })
          if (item.props) {
            if (item.props.branch) {
              methods.replacFlat(item.props.branch, list2)
            }
          }
          if (item.branch) {
            if (item.branch.length > 0) {
              item.branch.map((item1: any) => {
                methods.replacFlat(item1, list2)
              })
            }
          }
        })
        return list2
      },
      resetjumpNode(arr, list2) {
        arr.map((item: any) => {
          if (item.type == "TRIGGER") {
            list2.map((em: any) => {
              if (em.id == item.id) {
                item.props.jumpNodeCode = em.props.jumpNodeCode
              }

            })
          }
          if (item.props) {
            if (item.props.branch) {
              methods.resetjumpNode(item.props.branch, list2)
            }
          }
          if (item.branch) {
            if (item.branch.length > 0) {
              item.branch.map((item1: any) => {
                methods.resetjumpNode(item1, list2)
              })
            }
          }
        })
        return arr
      },
      edit(row: any) {
        router.push({ path: '/system/flowPath/flow/edit', query: { id: row.id } })
      }
    }
    return {
      ...toRefs(data),
      ...methods, Search, Plus,
      tableRef
    }
  }
})
</script>
<style scoped lang='scss'>
.box {
  width: calc(100% - 64px);
  background: #fff;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  height: 70px;
  padding: 10px 32px;
  margin-top: 10px;
}

.mytable {
  overflow-y: auto;
  width: calc(100% - 64px);
  background: #fff;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  padding: 10px 32px;
  height: calc(100% - 125px);
}
</style>